package com.qunar.wan.support.lucene;

import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.*;

import java.io.IOException;

/**
 * Created by hiCyoung on 13-12-1.
 */
public class HighLighter {
    public static String light(String text, Query query, String field) throws IOException, InvalidTokenOffsetsException {
        QueryScorer scorer = new QueryScorer(query);
        Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);
        Formatter formatter = new SimpleHTMLFormatter("<font color='orange'>", "</font>");
        Highlighter lighter = new Highlighter(formatter, scorer);
        lighter.setTextFragmenter(fragmenter);
        String ht = lighter.getBestFragment(LuceneContext.getAnalyzer(), field, text);
        if (ht == null) {
            return text.length() >= 100 ? text.substring(0, 100) : text;
        }
        return ht.trim();
    }

}
